
var sPop = null;
var postSubmited = false;
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = (userAgent.indexOf('opera') != -1);
var is_saf = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv = (userAgent.indexOf('webtv') != -1);
var is_ie = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4 = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon = (userAgent.indexOf('konqueror') != -1);
var is_ns = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4 = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac = (userAgent.indexOf('mac') != -1);

// ==menu 's == //
var menuOffX=0	//菜单距连接文字最左端距离
var menuOffY=20	//菜单距连接文字顶端距离
var ie4=document.all&&navigator.userAgent.indexOf("Opera")==-1
var ns6=document.getElementById&&!document.all
function showmenu(e,vmenu,mod){
	which=vmenu
	menuobj=document.getElementById("popmenu")
	menuobj.thestyle=menuobj.style
	menuobj.innerHTML=which
	menuobj.contentwidth=menuobj.offsetWidth
	eventX=e.clientX
	eventY=e.clientY
	var rightedge=document.body.clientWidth-eventX
	var bottomedge=document.body.clientHeight-eventY
	if (rightedge<menuobj.contentwidth)
		{
		menuobj.thestyle.left=document.body.scrollLeft+eventX-menuobj.contentwidth+menuOffX
		}
	else
		{
		menuobj.thestyle.left=ie4? ie_x(event.srcElement)+menuOffX : ns6? window.pageXOffset+eventX : eventX
		}
	if (bottomedge<menuobj.contentheight&&mod!=0)
		{
		menuobj.thestyle.top=document.body.scrollTop+eventY-menuobj.contentheight-event.offsetY+menuOffY-23
		}
	else
		{
		menuobj.thestyle.top=ie4? ie_y(event.srcElement)+menuOffY : ns6? window.pageYOffset+eventY+10 : eventY
		}
	menuobj.thestyle.visibility="visible"
}


function ie_y(e){  
	var t=e.offsetTop;  
	while(e=e.offsetParent){  
		t+=e.offsetTop;  
	}  
	return t;  
}  
function ie_x(e){  
	var l=e.offsetLeft;  
	while(e=e.offsetParent){  
		l+=e.offsetLeft;  
	}  
	return l;  
}

function highlightmenu(e,state){
	if (document.all)
		source_el=event.srcElement
		while(source_el.id!="popmenu"){
			source_el=document.getElementById? source_el.parentNode : source_el.parentElement
			if (source_el.className=="menuitems"){
				source_el.id=(state=="on")? "mouseoverstyle" : ""
		}
	}
}


function hidemenu(){if (window.menuobj)menuobj.thestyle.visibility="hidden"}
function dynamichide(e){if ((ie4||ns6)&&!menuobj.contains(e.toElement))hidemenu()}
document.onclick=hidemenu
document.write("<div class=menuskin id=popmenu onmouseover=highlightmenu(event,'on') onmouseout=highlightmenu(event,'off');dynamichide(event)></div>")
// 菜单END


//改变字体大小
function doZoom(size,name){
	document.getElementById('team'+ name).style.fontSize=size+'px';
}

function ctlent(event) {
	if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83)) {
		this.document.postform.postsubmit.disabled = true;
		this.document.postform.topicsreset.disabled = true;
		this.document.postform.submit();
	}
}

function storeCaret(textEl){
	if(textEl.createTextRange){
		textEl.caretPos = document.selection.createRange().duplicate();
	}
}

// ==msg 's== //
function checkclick(msg){
	if(confirm(msg))
		{
		event.returnValue=true;}else{event.returnValue=false;
		}
	}

// ==form 's== //
function checkall(form, prefix, checkall) {
	var checkall = checkall ? checkall : 'chkall';
	for(var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if(e.name != checkall && (!prefix || (prefix && e.name.match(prefix))))
		{
		e.checked = form.elements[checkall].checked;
		}
	}
}

function arraypop(a) {
	if(typeof a != 'object' || !a.length) {
		return null;
	} else {
		var response = a[a.length - 1];
		a.length--;
		return response;
	}
}

function arraypush(a, value) {
	a[a.length] = value;
	return a.length;
}


function findtags(parentobj, tag) {
	if(typeof parentobj.getElementsByTagName != 'undefined') {return parentobj.getElementsByTagName(tag);}
	else if(parentobj.all && parentobj.all.tags) {return parentobj.all.tags(tag);}
	else {return null;}
}

function copycode(obj) {
	var rng = document.body.createTextRange();
	rng.moveToElementText(obj);
	rng.scrollIntoView();
	rng.select();
	rng.execCommand("Copy");
	rng.collapse(false);
}

function toggle_collapse(objname, unfolded) {
	if(typeof unfolded == 'undefined') {
		var unfolded = 1;
	}
	var obj = document.getElementById(objname);
	var oldstatus = obj.style.display;
	var collapsed = getcookie('discuz_collapse');
	var cookie_start = collapsed ? collapsed.indexOf(objname) : -1;
	var cookie_end = cookie_start + objname.length + 1;

	obj.style.display = oldstatus == 'none' ? '' : 'none';
	collapsed = cookie_start != -1 && ((unfolded && oldstatus == 'none') || (!unfolded && oldstatus == '')) ?
			collapsed.substring(0, cookie_start) + collapsed.substring(cookie_end, collapsed.length) : (
			cookie_start == -1 && ((unfolded && oldstatus == '') || (!unfolded && oldstatus == 'none')) ?
			collapsed + objname + ' ' : collapsed);

	expires = new Date();
	expires.setTime(expires.getTime() + (collapsed ? 86400 * 30 : -(86400 * 30 * 1000)));
	document.cookie = 'discuz_collapse=' + escape(collapsed) + '; expires=' + expires.toGMTString() + '; path=/';

	var img = document.getElementById(objname + '_img');
	var img_regexp = new RegExp((oldstatus == 'none' ? '_yes' : '_no') + '\\.gif$');
	var img_re = oldstatus == 'none' ? '_no.gif' : '_yes.gif'
	if(img) {
		img.src = img.src.replace(img_regexp, img_re);
	}
}

function imgzoom(o) {
	if(event.ctrlKey) {
		var zoom = parseInt(o.style.zoom, 10) || 100;
		zoom -= event.wheelDelta / 12;
		if(zoom > 0) {
			o.style.zoom = zoom + '%';
		}
		return false;
	} else {
		return true;
	}
}

function AddText(txt) {
	obj = document.getElementById('postform').message;
	selection = document.selection;
	checkFocus();
	if(typeof(obj.selectionStart) != 'undefined') {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
	} else if(selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = txt;
		sel.moveStart('character', -mb_strlen(txt));
	} else {
		obj.value += txt;
	}
}

function insertAtCaret (textEl,	text){
	if(textEl.createTextRange && textEl.caretPos){
		var caretPos = textEl.caretPos;
		caretPos.text += caretPos.text.charAt(caretPos.text.length - 2)	== ' ' ? text +	' '	: text;
	} else if(textEl) {
		textEl.value +=	text;
	} else {
		textEl.value = text;
	}
}

function checkFocus() {
	var obj = typeof wysiwyg == 'undefined' || !wysiwyg ? document.getElementById('postform').message : editwin;
	if(!obj.hasfocus) {
		obj.focus();
	}
}

function closesmiliewindow(e) {
	if(typeof smiliewindow != 'undefined' && !smiliewindow.closed) {
		smiliewindow.close();
	}
}

function opensmiliewindow(width, height, editorid) {
	smiliewindow = window.open('post.php?action=smilies' + (editorid ? '&editorid=' + editorid : ''), 'Popup', 'width=' + width + ',height=' + height + ',resizable=yes,scrollbars=yes');
	window.onunload = closesmiliewindow;
}

function mb_strlen(str) {
	return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}

function insertSmiley(smilieid) {
	checkFocus();
	var src = document.getElementById('smilie_' + smilieid).src;
	var code = document.getElementById('smilie_' + smilieid).pop;
	if(typeof wysiwyg != 'undefined' && wysiwyg && allowsmilies && (!document.getElementById('smileyoff') || document.getElementById('smileyoff').checked == false)) {
		if(is_moz) {
			applyFormat('InsertImage', false, src);
			var smilies = findtags(editdoc.body, 'img');
			for(var i = 0; i < smilies.length; i++) {
				if(smilies[i].src == src && smilies[i].getAttribute('smilieid') < 1) {
					smilies[i].setAttribute('smilieid', smilieid);
					smilies[i].setAttribute('border', "0");
				}
			}
		} else {
			insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" /> ', false);
		}
	} else {
		code += ' ';
		AddText(code);
	}
}

function announcement() {
	document.getElementById('announcement').innerHTML = '<marquee style="filter:progid:DXImageTransform.Microsoft.Alpha(startX=0, startY=0, finishX=10, finishY=100,style=1,opacity=0,finishOpacity=100); margin: 0px 8px" direction="left" scrollamount="2" scrolldelay="1" onMouseOver="this.stop();" onMouseOut="this.start();">' +
		document.getElementById('announcement').innerHTML + '</marquee>';
	document.getElementById('announcement').style.display = 'block';
}
function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}
document.write("<style type='text/css' id='defaultPopStyle'>");
document.write(".cPopText { font-family: Tahoma, Verdana; background-color: #FFFFCC; border: 1px #000000 solid; font-size: 12px; padding-right: 4px; padding-left: 4px; line-height: 18px; padding-top: 2px; padding-bottom: 2px; visibility: hidden; filter: Alpha(Opacity=80)}");
document.write("</style>");
document.write("<div id='popLayer' style='position:absolute;z-index:1000' class='cPopText'></div>");

function showPopupText(event) {
	if(event.srcElement) o = event.srcElement; else o = event.target;
	if(!o) {
		return;
	}
	MouseX = event.clientX;
	MouseY = event.clientY;
	if(o.alt != null && o.alt != '') {
		o.pop = o.alt;
		o.alt = '';
	}
	if(o.title != null && o.title != '') {
		o.pop = o.title;
		o.title = '';
	}
	if(o.pop != sPop) {
		sPop = o.pop;
		if(sPop == null || sPop == '') {
			document.getElementById('popLayer').style.visibility = "hidden";
		} else {
			popStyle = o.dyclass != null ? o.dyclass : 'cPopText';
			document.getElementById('popLayer').style.visibility = "visible";
			showIt();
		}
	}
}

function showIt() {
	document.getElementById('popLayer').className = popStyle;
	document.getElementById('popLayer').innerHTML = sPop.replace(/<(.*)>/g,"&lt;$1&gt;").replace(/\n/g,"<br>");
	var popWidth = document.getElementById('popLayer').clientWidth;
	var popHeight = document.getElementById('popLayer').clientHeight;
	var popLeftAdjust = MouseX + 12 + popWidth > document.body.clientWidth ? -popWidth - 24 : 0;
	var popTopAdjust = MouseY + 12 + popHeight > document.body.clientHeight ? -popHeight - 24 : 0;
	document.getElementById('popLayer').style.left = (MouseX + 12 + document.body.scrollLeft + popLeftAdjust) + 'px';
	document.getElementById('popLayer').style.top = (MouseY + 12 + document.body.scrollTop + popTopAdjust) + 'px';
}

if(!document.onmouseover) {
	document.onmouseover = function(e) {
		var event = e ? e : window.event;
		showPopupText(event);
	};
}


// ==page's== //
function showPages(name) { //初始化属性
 this.name = name;      //对象名称
 this.page = 1;         //当前页数
 this.pageCount = 1;    //总页数
 this.dispCount = 1;    //所有贴数
 this.argName = 'page'; //参数名
 this.showTimes = 1;    //打印次数
}

showPages.prototype.getPage = function(){ //丛url获得当前页数,如果变量重复只获取最后一个
 var args = location.search;
 var reg = new RegExp('[\?&]?' + this.argName + '=([^&]*)[&$]?', 'gi');
 var chk = args.match(reg);
 this.page = RegExp.$1;
}

showPages.prototype.checkPages = function(){ //进行当前页数和总页数的验证
 if (isNaN(parseInt(this.page))) this.page = 1;
 if (isNaN(parseInt(this.pageCount))) this.pageCount = 1;
 if (this.page < 1) this.page = 1;
 if (this.pageCount < 1) this.pageCount = 1;
 this.page = parseInt(this.page);
 this.pageCount = parseInt(this.pageCount);
 if (this.page > this.pageCount) this.page = this.pageCount;
}

showPages.prototype.createHtml = function(mode){ //生成html代码

	var ispages = parseInt(this.page);
     var strHtml = '', prevPage = ispages - 1, nextPage = ispages + 1;
	 strHtml += '<table width="100%" cellspacing="0" cellpadding="0" align="center" style="margin-bottom: 4px"><tr><td valign="bottom"><div class="p_bar"> <a class="p_total">' + this.dispCount + '</a> <a class="p_pages">' + ispages + '/' + this.pageCount + '</a>';
     if (prevPage < 1) {
       strHtml += '<a class="p_num">&#171;</a>';
       strHtml += '<a class="p_num">&#139;</a>';
     } else {
       strHtml += '<a href="javascript:' + this.name + '.toPage(1);" class="p_num">&#171;</a>';
       strHtml += '<a href="javascript:' + this.name + '.toPage(' + prevPage + ');" class="p_num">&#139;</a>';
     }

     if (ispages % 10 ==0) {
       var startPage = ispages - 9;
     } else {
       var startPage = ispages - ispages % 10 + 1;
     }
     if (startPage > 10) strHtml += '<a href="javascript:' + this.name + '.toPage(' + (startPage - 1) + ');" class="p_num">...</a>';

     for (var i = startPage; i < startPage + 10; i++) {
       if (i > this.pageCount) break;
       if (i == ispages) {
         strHtml += '<a class="p_curpage" title="Page ' + i + '" >' + i + '</a>';
       } else {
         strHtml += '<span title="Page ' + i + '"><a href="javascript:' + this.name + '.toPage(' + i + ');" class="p_num">' + i + '</a></span>';
       }
     }

     if (this.pageCount >= startPage + 10) strHtml += '<span title="Next 10 Pages"><a href="javascript:' + this.name + '.toPage(' + (startPage + 10) + ');" class="p_num">...</a></span>';
     if (nextPage > this.pageCount) {
       strHtml += '<a class="p_num" title="Next Page">&#155;</a>';
       strHtml += '<a class="p_num" title="Last Page">&#187;</a>';
     } else {
       strHtml += '<span  title="Next Page"><a class="p_num" href="javascript:' + this.name + '.toPage(' + nextPage + ');">&#155;</a></span>';
       strHtml += '<span title="Last Page"><a class="p_num" href="javascript:' + this.name + '.toPage(' + this.pageCount + ');">&#187;</a></span>';
     }
	 strHtml += '<input type="text" id="pageInput' + this.showTimes + '" value="' + ispages + '" title="Input page" onkeypress="return ' + this.name + '.formatInputPage(event);" onfocus="this.select()" size="1"> <input type="button" name="go" value="GO" onclick="' + this.name + '.toPage(document.getElementById(\'pageInput' + this.showTimes + '\').value);"></div></td><td align="right" valign="bottom"></td></tr></table>';
 return strHtml;
}

showPages.prototype.createUrl = function (page) { //生成页面跳转url
 if (isNaN(parseInt(page))) page = 1;
 if (page < 1) page = 1;
 if (page > this.pageCount) page = this.pageCount;
 var url = location.protocol + '//' + location.host + location.pathname;
 var args = location.search;
 var reg = new RegExp('([\?&]?)' + this.argName + '=[^&]*[&$]?', 'gi');
 args = args.replace(reg,'$1');
 if (args == '' || args == null) {
   args += '?' + this.argName + '=' + page;
 } else if (args.substr(args.length - 1,1) == '?' || args.substr(args.length - 1,1) == '&') {
     args += this.argName + '=' + page;
 } else {
     args += '&' + this.argName + '=' + page;
 }
 return url + args;
}

showPages.prototype.toPage = function(page){ //页面跳转
 var turnTo = 1;
 if (typeof(page) == 'object') {
   turnTo = page.options[page.selectedIndex].value;
 } else {
   turnTo = page;
 }
 self.location.href = this.createUrl(turnTo);
}

showPages.prototype.printHtml = function(mode){ //显示html代码
 this.getPage();
 this.checkPages();
 this.showTimes += 1;
 document.write('<div id="pages_' + this.name + '_' + this.showTimes + '" class="a4"></div>');
 document.getElementById('pages_' + this.name + '_' + this.showTimes).innerHTML = this.createHtml(mode);
}

showPages.prototype.formatInputPage = function(e){ //限定输入页数格式
 var ie = navigator.appName=="Microsoft Internet Explorer"?true:false;
 if(!ie) var key = e.which;
 else var key = event.keyCode;
 if (key == 8 || key == 46 || (key >= 48 && key <= 57)) return true;
 return false;
}

	//Ajax
  function ajaxRead(file,fun){
   var xmlObj = null;
   if(window.XMLHttpRequest){
      xmlObj = new XMLHttpRequest();
   } else if(window.ActiveXObject){
      xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      return;
   }

   xmlObj.onreadystatechange = function(){
    if(xmlObj.readyState == 4){
		if (xmlObj.status ==200){
			obj = xmlObj.responseXML;
			eval(fun);
		}
		else{
			alert("读取文件出错,错误号为 [" + xmlObj.status  + "]");
		}
    }
   }
   xmlObj.open ('GET', file, true);
   xmlObj.send (null);
  }
/********************************/
var menuslidetimer = null;

function Popup_Handler() {
	this.open_steps = 2;
	this.open_fade = false;
	this.active = false;
	this.menus = new Array();
	this.activemenu = null;
	this.hidden_selects = new Array();

	this.activate = function(active) {
		this.active = active;
	}

	this.register = function(clickactive, controlkey, noimage) {
		this.menus[controlkey] = new Popup_Menu(clickactive, controlkey, noimage);
		return this.menus[controlkey];
	}

	this.hide = function() {
		if(this.activemenu != null) this.menus[this.activemenu].hide();
	}
}

function Popup_Events() {
	this.controlobj_show = function(e) {
		doane(e);
		clearTimeout(this.slidetimer);
		if(popupmenu.activemenu == null || popupmenu.menus[popupmenu.activemenu].controlkey != this.id)	{popupmenu.menus[this.id].show(this, false, popupmenu.menus[this.id].clickactive);}
	}

	this.controlobj_onclick = function(e) {
		doane(e);
		if(popupmenu.activemenu == null || popupmenu.menus[popupmenu.activemenu].controlkey != this.id)	{popupmenu.menus[this.id].show(this, false, popupmenu.menus[this.id].clickactive);}
		else {popupmenu.menus[this.id].hide();}
	}

	this.controlobj_onmouseover = function(e) {
		doane(e);
		popupmenu.menus[this.id].hover(this);
	}

	this.menuoption_onclick_function = function(e) {
		this.ofunc(e);
		popupmenu.menus[this.controlkey].hide();
	}

	this.menuoption_onclick_link = function(e) {
		popupmenu.menus[this.controlkey].choose(e, this);
	}

	this.menuoption_onmouseover = function(e) {
		this.className = 'popupmenu_highlight';
	}

	this.menuoption_onmouseout = function(e) {
		this.className = 'popupmenu_option';
	}
}

popupmenu = new Popup_Handler();
popupevents = new Popup_Events();

function popupmenu_hide(e) {
	if(e && e.button && e.button != 1 && e.type == 'click')  return true;
	else popupmenu.hide();
}

function Popup_Menu(clickactive, controlkey, noimage) {
	this.controlkey = controlkey;
	this.clickactive = clickactive;
	this.menuname = this.controlkey.split('.')[0] + '_menu';
	if(document.getElementById(this.menuname)) {this.init_menu(clickactive);}
	this.slide_open = (is_opera ? false : true);
	this.open_steps = popupmenu.open_steps;

	this.init_control = function(noimage) {
		this.controlobj = document.getElementById(this.controlkey);
		this.controlobj.state = false;
		if(this.controlobj.firstChild && (this.controlobj.firstChild.tagName == 'TEXTAREA' || this.controlobj.firstChild.tagName == 'INPUT')) {
		} else {
			if(!this.clickactive && !noimage && !(is_mac && is_ie)) {
				var img = document.createElement('img');
				img.src = 'images/common/jsmenu.gif';
				img.border = 0;
				img.title = '';
				img.alt = '';
				this.controlobj.appendChild(img);
			}
			this.controlobj.unselectable = true;
			if(!noimage) {
				this.controlobj.style.cursor = is_ie ? 'hand' : 'pointer';
			}
			if(clickactive) {
				this.controlobj.onclick = popupevents.controlobj_onclick;
				this.controlobj.onmouseover = popupevents.controlobj_onmouseover;
			} else {
				this.controlobj.onmouseover = popupevents.controlobj_show;
			}
		}
	}

	this.init_control( noimage);

	this.init_menu = function() {
		this.menuobj = document.getElementById(this.menuname);
		if(this.menuobj && !this.menuobj.initialized) {
			this.menuobj.initialized = true;
			this.menuobj.onclick = ebygum;
			this.menuobj.style.position = 'absolute';
			if(!this.clickactive) {
				this.menuobj.onmouseover = function() {
					clearTimeout(menuslidetimer);
				}
				this.menuobj.onmouseout = function() {
					menuslidetimer = setTimeout("menuhide()",500);
				}
			}
			this.menuobj.style.zIndex = 50;
			if(is_ie && !is_mac) {
				this.menuobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
			}
			this.init_menu_contents();
		}
	}

	this.init_menu_contents = function() {
		var tds = findtags(this.menuobj, 'td');
		for(var i = 0; i < tds.length; i++) {
			if(tds[i].className == 'popupmenu_option' || tds[i].className == 'editor_colornormal') {
				if(is_ie && !is_mac) {
					tds[i].style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=85,finishOpacity=100,style=0)";
				}
				tds[i].style.opacity = 0.85;
				if(tds[i].title && tds[i].title == 'nohighlight') {
					tds[i].title = '';
				} else {
					tds[i].controlkey = this.controlkey;
					if(tds[i].className != 'editor_colornormal') {
						tds[i].onmouseover = popupevents.menuoption_onmouseover;
						tds[i].onmouseout = popupevents.menuoption_onmouseout;
					}
					if(typeof tds[i].onclick == 'function') {
						tds[i].ofunc = tds[i].onclick;
						tds[i].onclick = popupevents.menuoption_onclick_function;
					} else {
						tds[i].onclick = popupevents.menuoption_onclick_link;
					}
					if(!is_saf && !is_kon)	{
						try {
							links = findtags(tds[i], 'a');
							for(var j = 0; j < links.length; j++) {
								if(typeof links[j].onclick  == 'undefined') links[j].onclick = ebygum;
							}
						}
						catch(e) {}
					}
				}
			}
		}
	}

	this.show = function(obj, instant) {
		if(!popupmenu.active){return false;}
		else if(!this.menuobj)	{this.init_menu();}
		if(!this.menuobj) {return false;}
		if(popupmenu.activemenu != null) {popupmenu.menus[popupmenu.activemenu].hide();}
		popupmenu.activemenu = this.controlkey;
		this.menuobj.style.display = '';
		if(popupmenu.slide_open) {this.menuobj.style.clip = 'rect(auto, auto, auto, auto)';}
		this.pos = this.fetch_offset(obj);
		this.leftpx = this.pos['left'];
		this.toppx = this.pos['top'] + obj.offsetHeight;
		if((this.leftpx + this.menuobj.offsetWidth) >= document.body.clientWidth && (this.leftpx + obj.offsetWidth - this.menuobj.offsetWidth) > 0) {
			this.leftpx = this.leftpx + obj.offsetWidth - this.menuobj.offsetWidth;
			this.direction = 'right';
		} else {this.direction = 'left';}
		this.menuobj.style.left = this.leftpx + 'px';
		this.menuobj.style.top  = this.toppx + 'px';
		if(!instant && this.slide_open) {
			this.intervalX = Math.ceil(this.menuobj.offsetWidth / this.open_steps);
			this.intervalY = Math.ceil(this.menuobj.offsetHeight / this.open_steps);
			this.slide((this.direction == 'left' ? 0 : this.menuobj.offsetWidth), 0, 0);
		} else if(this.menuobj.style.clip && popupmenu.slide_open) {
			this.menuobj.style.clip = 'rect(auto, auto, auto, auto)';
		}
		this.handle_overlaps(true);
		if(this.menuobj.scrollHeight > 400) {
			this.menuobj.style.height = '400px';
			if(is_ie || is_opera) {
				this.menuobj.style.width = this.menuobj.scrollWidth + 18;
			}
			if(is_opera) {
				this.menuobj.style.overflow = 'scroll';
			} else {
				this.menuobj.style.overflowY = 'scroll';
			}
		}
	}

	this.hide = function(e) {
		if(e && e.button && e.button != 1) {return true;}
		this.stop_slide();
		this.menuobj.style.display = 'none';
		this.handle_overlaps(false);
		popupmenu.activemenu = null;
	}

	this.slidehide = function() {
		popupmenu.menus[popupmenu.activemenu].hide()
	}

	this.hover = function(obj, clickactive) {
		if(popupmenu.activemenu != null) {
			if(popupmenu.menus[popupmenu.activemenu].controlkey != this.id) {this.show(obj, true, clickactive);}
		}
	}

	this.choose = function(e, obj) {
		var links = findtags(obj, 'a');
		if(links[0]) {
			if(is_ie) {
				links[0].click();
				window.event.cancelBubble = true;
			} else {
				if(e.shiftKey) {
					window.open(links[0].href);
					e.stopPropagation();
					e.preventDefault();
				} else {
					window.location = links[0].href;
					e.stopPropagation();
					e.preventDefault();
				}
			}
			this.hide();
		}
	}

	this.slide = function(clipX, clipY, opacity) {
		if(this.direction == 'left' && (clipX < this.menuobj.offsetWidth || clipY < this.menuobj.offsetHeight)) {
			if(popupmenu.open_fade && is_ie) {
				opacity += 10;
				this.menuobj.filters.item('DXImageTransform.Microsoft.alpha').opacity = opacity;
			}
			clipX += this.intervalX;
			clipY += this.intervalY;
			this.menuobj.style.clip = "rect(auto, " + clipX + "px, " + clipY + "px, auto)";
			this.slidetimer = setTimeout("popupmenu.menus[popupmenu.activemenu].slide(" + clipX + ", " + clipY + ", " + opacity + ");", 0);
		} else if(this.direction == 'right' && (clipX > 0 || clipY < this.menuobj.offsetHeight)) {
			if(popupmenu.open_fade && is_ie) {
				opacity += 10;
				menuobj.filters.item('DXImageTransform.Microsoft.alpha').opacity = opacity;
			}
			clipX -= this.intervalX;
			clipY += this.intervalY;
			this.menuobj.style.clip = "rect(auto, " + this.menuobj.offsetWidth + "px, " + clipY + "px, " + clipX + "px)";
			this.slidetimer = setTimeout("popupmenu.menus[popupmenu.activemenu].slide(" + clipX + ", " + clipY + ", " + opacity + ");", 0);
		} else {this.stop_slide();}
	}

	this.stop_slide = function() {
		clearTimeout(this.slidetimer);
		this.menuobj.style.clip = 'rect(auto, auto, auto, auto)';
		if(popupmenu.open_fade && is_ie) {this.menuobj.filters.item('DXImageTransform.Microsoft.alpha').opacity = 100;}
	}

	this.fetch_offset = function(obj) {
		var left_offset = obj.offsetLeft;
		var top_offset = obj.offsetTop;
		while ((obj = obj.offsetParent) != null) {
			left_offset += obj.offsetLeft;
			top_offset += obj.offsetTop;
		}
		return { 'left' : left_offset, 'top' : top_offset };
	}

	this.overlaps = function(obj, m) {
		var s = new Array();
		var pos = this.fetch_offset(obj);
		s['L'] = pos['left'];
		s['T'] = pos['top'];
		s['R'] = s['L'] + obj.offsetWidth;
		s['B'] = s['T'] + obj.offsetHeight;
		if(s['L'] > m['R'] || s['R'] < m['L'] || s['T'] > m['B'] || s['B'] < m['T']) {return false;}
		return true;
	}

	this.handle_overlaps = function(dohide) {
		if(is_ie) {
			var selects = findtags(document, 'select');
			if(dohide) {
				var menuarea = new Array(); menuarea = {
					'L' : this.leftpx,
					'R' : this.leftpx + this.menuobj.offsetWidth,
					'T' : this.toppx,
					'B' : this.toppx + this.menuobj.offsetHeight
				};
				for(var i = 0; i < selects.length; i++) {
					if(this.overlaps(selects[i], menuarea)) {
						var hide = true;
						var s = selects[i];
						while (s = s.parentNode) {
							if(s.className == 'popupmenu_popup') {
								hide = false;
								break;
							}
						}
						if(hide) {
							selects[i].style.visibility = 'hidden';
							arraypush(popupmenu.hidden_selects, i);
						}
					}
				}
			} else {
				while (true) {
					var i = arraypop(popupmenu.hidden_selects);
					if(typeof i == 'undefined' || i == null) break;
					else selects[i].style.visibility = 'visible';
				}
			}
		}
	}
}

function doane(eventobj) {
	if(!eventobj || is_ie)	{
		window.event.returnValue = false;
		window.event.cancelBubble = true;
		return window.event;
	} else {
		eventobj.stopPropagation();
		eventobj.preventDefault();
		return eventobj;
	}
}

function ebygum(eventobj) {
	if(!eventobj || is_ie) {
		window.event.cancelBubble = true;
		return window.event;
	} else {
		if(eventobj.target.type == 'submit')  eventobj.target.form.submit();
		eventobj.stopPropagation();
		return eventobj;
	}
}

function menuregister(clickactive, controlid, noimage, datefield) {
	if(typeof popupmenu == 'object') {
		popupmenu.register(clickactive, controlid, noimage);
	}
}

function menuhide() {
	if(popupmenu.activemenu != null) {
		popupmenu.menus[popupmenu.activemenu].slidehide();
	}
}

if(typeof popupmenu == 'object') {
	if(window.attachEvent && !is_saf) {
		document.attachEvent('onclick', popupmenu_hide);
		window.attachEvent('onresize', popupmenu_hide);
	} else if(document.addEventListener && !is_saf) {
		document.addEventListener('click', popupmenu_hide, false);
		window.addEventListener('resize', popupmenu_hide, false);
	} else {
		window.onclick = popupmenu_hide;
		window.onresize = popupmenu_hide;
	}
	popupmenu.activate(true);
}
/**********************************************************************/
var re;
var pcodecount = '-1';
var codecount = 0;
var codehtml = new Array();
var prepend = '';
var append = '';

function addslashes(str) {
	var searcharray = ['\\', '\'', '/', '(', ')', '[', ']', '{', '}', '^', '$', '?', '.', '*', '+', '|'];
	var replacearray = ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|'];
	var len = searcharray.length;
	for(var i = 0; i < len; i++) {
		if(str)
		str = str.replace(searcharray[i], replacearray[i]);
	}

	return str;
}

function atag(aoptions, text) {
	if(trim(text) == '') {
		return '';
	}

	href = getoptionvalue('href', aoptions);

	if(href.substr(0, 11) == 'javascript:') {
		return trim(recursion('a', text, 'atag'));
	} else if(href.substr(0, 7) == 'mailto:') {
		tag = 'email';
		href = href.substr(7);
	} else {
		tag = 'url';
	}

	return '[' + tag + '=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/' + tag + ']';
}
function bbcode2html(str) {

	str = trim(str);

	if(str == '') {
		return '';
	}

	if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
		str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return parsecode($2);});
	}

	if(!forumallowhtml && !(allowhtml && fetchCheckbox('htmlon'))) {
		str = str.replace(/</ig, '&lt;');
		str = str.replace(/>/ig, '&gt;');
	}

	if(!fetchCheckbox('smileyoff') && allowsmilies) {
		for(id in smilies) {
			if(smilies[id]['code']){
			re = new RegExp(addslashes(smilies[id]['code']), "g");
			
			str = str.replace(re, '<img src="images/Emotions/' + smilies[id]['url'] + '" border="0" smilieid="' + id + '" alt="' + smilies[id]['code'] + '" />');
			}
		}

	}

	if(!fetchCheckbox('parseurloff')) {
		str = str.replace(/^((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)/ig, '<a href="$1" target="_blank">$1</a>');
		str = str.replace(/((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)$/ig, '<a href="$1" target="_blank">$1</a>');
		str = str.replace(/[^>=\]""]((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)/ig, '<a href="$1" target="_blank">$1</a>');
	}

	if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
		str= str.replace(/\[url\]\s*(www.|https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|ed2k:\/\/){1}([^\[\"']+?)\s*\[\/url\]/ig, function($1, $2, $3) {return cuturl($2 + $3);});
		str= str.replace(/\[url=www.([^\[\"']+?)\](.+?)\[\/url\]/ig, '<a href="http://www.$1" target="_blank">$2</a>');
		str= str.replace(/\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|ed2k){1}:\/\/([^\[\"']+?)\]([\s\S]+?)\[\/url\]/ig, '<a href="$1://$2" target="_blank">$3</a>');

		str= str.replace(/\[email\](.*?)\[\/email\]/ig, '<a href="mailto:$1">$1</a>');

		str= str.replace(/\[email=(.[^\[]*)\](.*?)\[\/email\]/ig, '<a href="mailto:$1" target="_blank">$2</a>');

		str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">');

		str = str.replace(/\[size=(\d+?)\]/ig, '<font size="$1">');
		str = str.replace(/\[size=(\d+(px|pt|in|cm|mm|pc|em|ex|%)+?)\]/ig, '<font style="font-size: $1">');
		str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">');
		str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<p align="$1">');

		re = /\s*\[table(=(\d{1,3}%?))?\][\n\r]*([\s\S]+?)[\n\r]*\[\/table\]\s*/ig;
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);});
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);});
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);});
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);});

		var searcharray = new Array(
			'\\\[\\\/color\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
			'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
			'\\\[list=A\\\]', '\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]'
		);
		var replacearray = new Array(
			'</font>', '</font>', '</font>', '</p>', '<b>', '</b>', '<i>',
			'</i>', '<u>', '</u>', '<ul>', '<ol type=1>', '<ol type=a>',
			'<ol type=A>', '<li>', '</ul></ol>', '<blockquote>', '</blockquote>'
		);
		var len = searcharray.length;
		for(var i = 0; i < len; i++) {
			re = new RegExp(searcharray[i], "ig");
			str = str.replace(re, replacearray[i]);
		}
	}

	if(!fetchCheckbox('bbcodeoff')) {
		if(allowimgcode) {
			str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src="$1" border="0" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}" onmouseover="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor=\'hand\'; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}" onclick="if(!this.resized) {return true;} else {window.open(\'$1\');}" onmousewheel="return imgzoom(this);" alt="" />');
			str = str.replace(/\[img=(\d{1,3})[x|\,](\d{1,3})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img width="$1" height="$2" src="$3" border="0" alt="" />');

		} else {
			str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
			str = str.replace(/\[img=(\d{1,3})[x|\,](\d{1,3})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
		}
	}

	for(var i = 0; i <= pcodecount; i++) {
		str = str.replace("[\tWEB_CODE_" + i + "\t]", codehtml[i]);
	}

	if(!forumallowhtml && !(allowhtml && fetchCheckbox('htmlon'))) {
		str = str.replace(/\t/ig, '&nbsp; &nbsp; &nbsp; &nbsp; ');
		str = str.replace(/   /ig, '&nbsp; &nbsp;');
		str = str.replace(/  /ig, '&nbsp;&nbsp;');
		str = str.replace(/\r\n/ig, '<br />');
		str = str.replace(/[\r\n]/ig, '<br />');
	}
	return(str);
}

function codetag(text) {
	pcodecount++;

	text = text.replace(/<br[^\>]*>/ig, "\n");
	text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
	text = text.replace(/<(\/|)[A-Za-z].*?>/ig, '');

	codehtml[pcodecount] = "[code]" + text + "[/code]";
	codecount++;
	return "[\tWEB_CODE_" + pcodecount + "\t]";
}

function cuturl(url) {
	var length = 65;
	var urllink = '<a href="' + (url.toLowerCase().substr(0, 4) == 'www.' ? 'http://' + url : url) + '" target="_blank">';
	if(url.length > length) {
		url = url.substr(0, parseInt(length * 0.5)) + ' ... ' + url.substr(url.length - parseInt(length * 0.3));
	}
	urllink += url + '</a>';
	return urllink;
}

function dpstag(options, text, tagname) {
	prepend = append = '';
	parsestyle(options, append);
	if(in_array(tagname, ['div', 'p'])) {
		align = getoptionvalue('align', options);
		if(in_array(align, ['left', 'center', 'right'])) {
			prepend = '[align=' + align + ']' + prepend;
			append += '[/align]';
		} else {
			append += "\n";
		}
	}
	return prepend + recursion(tagname, text, 'dpstag') + append;
}

function fetchCheckbox(cbn) {
	return document.getElementById(cbn) && document.getElementById(cbn).checked == true ? 1 : 0;
}

function fetchoptionvalue(option, text) {
	if((position = strpos(text, option)) !== false) {
		delimiter = position + option.length;
		if(text.charAt(delimiter) == '"') {
			delimchar = '"';
		} else if(text.charAt(delimiter) == '\'') {
			delimchar = '\'';
		} else {
			delimchar = ' ';
		}
		delimloc = strpos(text, delimchar, delimiter + 1);
		if(delimloc === false) {
			delimloc = text.length;
		} else if(delimchar == '"' || delimchar == '\'') {
			delimiter++;
		}
		return trim(text.substr(delimiter, delimloc - delimiter));
	} else {
		return '';
	}
}

function fonttag(fontoptions, text) {
	prepend = append = '';
	var tags = new Array();
	tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
	for(bbcode in tags) {
		optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
		if(optionvalue) {
			prepend += '[' + bbcode + '=' + optionvalue + ']';
			append = '[/' + bbcode + ']' + append;
		}
	}

	parsestyle(fontoptions, append);
	return prepend + recursion('font', text, 'fonttag') + append;
}

function getoptionvalue(option, text) {
	re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
	var matches = re.exec(text);
	if(matches != null && matches.length) {
		return trim(matches[3]);
	}
	return '';
}

function html2bbcode(str) {

	str = trim(str);

	if(str == '' || forumallowhtml || (allowhtml && fetchCheckbox('htmlon'))) {
		return str;
	}

	str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
	str = str.replace(/<style.*?>[\s\S]*?<\/style>/ig, '');
	str = str.replace(/<script.*?>[\s\S]*?<\/script>/ig, '');
	str = str.replace(/<noscript.*?>[\s\S]*?<\/noscript>/ig, '');
	str = str.replace(/<select.*?>[\s\S]*?<\/select>/ig, '');
	str = str.replace(/<object.*?>[\s\S]*?<\/object>/ig, '');
	str = str.replace(/<!--[\s\S]*?-->/ig, '');
	str = str.replace(/on(mousewheel|mouseover|click|load|unload|submit|focus|blur)="[^"]*"/ig, '');
	str = str.replace(/(\r\n|\n|\r)/ig, '');

	str = str.replace(/<table([^>]*width[^>]*)>/ig, function($1, $2) {return tabletag($2);});
	str = str.replace(/<table[^>]*>/ig, '[table]');
	str = str.replace(/<tr[^>]*>/ig, '[tr]');
	str = str.replace(/<td>/ig, '[td]');
	str = str.replace(/<td([^>]+)>/ig, function($1, $2) {return tdtag($2);});
	str = str.replace(/<\/td>/ig, '[/td]');
	str = str.replace(/<\/tr>/ig, '[/tr]');
	str = str.replace(/<\/table>/ig, '[/table]');

	str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
	str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smilies[$3]['code'];});
	str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
	str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, "$3");
	str = str.replace(/<br[^\>]*>/ig, "\n");

	str = recursion('b', str, 'simpletag', 'b');
	str = recursion('strong', str, 'simpletag', 'b');
	str = recursion('i', str, 'simpletag', 'i');
	str = recursion('em', str, 'simpletag', 'i');
	str = recursion('u', str, 'simpletag', 'u');
	str = recursion('a', str, 'atag');
	str = recursion('font', str, 'fonttag');
	str = recursion('blockquote', str, 'simpletag', 'quote');
	str = recursion('ol', str, 'listtag');
	str = recursion('ul', str, 'listtag');
	str = recursion('div', str, 'dpstag');
	str = recursion('p', str, 'dpstag');
	str = recursion('span', str, 'dpstag');

	str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');

	for(var i = 0; i <= pcodecount; i++) {
		str = str.replace("[\tWEB_CODE_" + i + "\t]", codehtml[i]);
	}

	str = str.replace(/&amp;/ig, '&');
	str = str.replace(/&nbsp;/ig, ' ');
	str = str.replace(/&lt;/ig, '<');
	str = str.replace(/&gt;/ig, '>');

	return str
}

function htmlspecialchars(str) {

	var f = new Array(
		(is_mac && is_ie ? new RegExp('&', 'g') : new RegExp('&(?!#[0-9]+;)', 'g')),
		new RegExp('<', 'g'),
		new RegExp('>', 'g'),
		new RegExp('"', 'g')
	);
	var r = new Array(
		'&amp;',
		'&lt;',
		'&gt;',
		'&quot;'
	);

	for(var i = 0; i < f.length; i++) {
		str = str.replace(f[i], r[i]);
	}

	return str;
}

function imgtag(attributes) {
	var width = '';
	var height = '';

	re = /src=(["']?)([\s\S]*?)(\1)/i;
	var matches = re.exec(attributes);
	if(matches != null) {
		var src = matches[2];
	} else {
		return '';
	}

	re = /width=(["']?)(\d+)(\1)/i;
	var matches = re.exec(attributes);
	if(matches != null) {
		width = matches[2];
	}

	re = /height=(["']?)(\d+)(\1)/i;
	var matches = re.exec(attributes);
	if(matches != null) {
		height = matches[2];
	}

	return width > 0 && height > 0 ?
		'[img=' + width + ',' + height + ']' + src + '[/img]' :
		'[img]' + src + '[/img]';
}

function listtag(listoptions, text, tagname) {
	text = text.replace(/<li>(([\s\S](?!<\/li))*?)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (is_opera ? '</li>' : '');
	text = recursion('li', text, 'litag');
	var opentag = '[list]';
	if(tagname == 'ol') {
		var listtype = fetchoptionvalue('type=', listoptions);
		listtype = listtype != '' ? listtype : '1';
		if(in_array(listtype, ['1', 'a', 'A'])) {
			opentag = '[list=' + listtype + ']';
		}
	}
	return text ? opentag + recursion(tagname, text, 'listtag') + '[/list]' : '';
}

function litag(listoptions, text) {
	return '[*]' + text.replace(/(\s+)$/g, '');
}

function parsecode(text) {
	pcodecount++;

	text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
	text = htmlspecialchars(text);

	codehtml[pcodecount] = '[code]' + text + '[/code]';

	codecount++;
	return "[\tWEB_CODE_" + pcodecount + "\t]";
}

function parsestyle(tagoptions, appendtags) {
	var searchlist = [
		['align', true, 'text-align:\\s*(left|center|right);?', 1],
		['color', true, '^(?:\\s|)color:\\s*([^;]+);?', 1],
		['font', true, 'font-family:\\s*([^;]+);?', 1],
		['size', true, 'font-size:\\s*(\\d+(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
		['b', false, 'font-weight:\\s*(bold);?'],
		['i', false, 'font-style:\\s*(italic);?'],
		['u', false, 'text-decoration:\\s*(underline);?']
	];
	var style = getoptionvalue('style', tagoptions);
	re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/ig;
	style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});
	var len = searchlist.length;
	for(var i = 0; i < len; i++) {
		re = new RegExp(searchlist[i][2], "ig");
		match = re.exec(style);
		if(match != null) {
			opnvalue = match[searchlist[i][3]];
			prepend += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
			append = '[/' + searchlist[i][0] + ']' + appendtags;
		}
	}
}

function parsetable(width, str) {
	if(typeof width == 'undefined') {
		var width = '';
	} else {
		width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
	}

	var string = '<table '
		+ (width == '' ? '' : 'width="' + width + '" ')
		+ 'align="center" class="t_table">';

	str = str.replace(/\[td=(\d{1,2}),(\d{1,2})(,(\d{1,3}%?))?\]/ig, '<td colspan="$1" rowspan="$2" width="$4">');
	str = str.replace(/\[tr\]/ig, '<tr>');
	str = str.replace(/\[td\]/ig, '<td>');
	str = str.replace(/\[\/td\]/ig, '</td>');
	str = str.replace(/\[\/tr\]/ig, '</tr>');

	string += str;
	string += '</table>';

	return string;
}

function recursion(tagname, text, dofunction, extraargs) {
	if(extraargs == null) {
		extraargs = '';
	}
	tagname = tagname.toLowerCase();

	var open_tag = '<' + tagname;
	var open_tag_len = open_tag.length;
	var close_tag = '</' + tagname + '>';
	var close_tag_len = close_tag.length;
	var beginsearchpos = 0;

	do {
		var textlower = text.toLowerCase();
		var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
		if(tagbegin == -1) {
			break;
		}

		var strlen = text.length;

		var inquote = '';
		var found = false;
		var tagnameend = false;
		var optionend = 0;
		var t_char = '';

		for(optionend = tagbegin; optionend <= strlen; optionend++) {
			t_char = text.charAt(optionend);
			if((t_char == '"' || t_char == "'") && inquote == '') {
				inquote = t_char;
			} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
				inquote = '';
			} else if(t_char == '>' && !inquote) {
				found = true;
				break;
			} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
				tagnameend = optionend;
			}
		}

		if(!found) {
			break;
		}
		if(!tagnameend) {
			tagnameend = optionend;
		}

		var offset = optionend - (tagbegin + open_tag_len);
		var tagoptions = text.substr(tagbegin + open_tag_len, offset)
		var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);

		if(acttagname != tagname) {
			beginsearchpos = optionend;
			continue;
		}

		var tagend = textlower.indexOf(close_tag, optionend);
		if(tagend == -1) {
			break;
		}

		var nestedopenpos = textlower.indexOf(open_tag, optionend);
		while(nestedopenpos != -1 && tagend != -1) {
			if(nestedopenpos > tagend) {
				break;
			}
			tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
			nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
		}

		if(tagend == -1) {
			beginsearchpos = optionend;
			continue;
		}

		var localbegin = optionend + 1;
		var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);

		text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);

		beginsearchpos = tagbegin + localtext.length;

	} while(tagbegin != -1);

	return text;
}

function simpletag(options, text, tagname, parseto) {
	if(trim(text) == '') {
		return '';
	}
	text = recursion(tagname, text, 'simpletag', parseto);
	return '[' + parseto + ']' + text + '[/' + parseto + ']';
}

function strpos(haystack, needle, offset) {
	if(typeof offset == 'undefined') {
		offset = 0;
	}

	index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return index == -1 ? false : index;
}

function tabletag(attributes) {
	var width = '';
	re = /width=(["']?)(\d{1,3}%?)(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null && matches.length) {
		width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
			(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
			(matches[2] <= 560 ? matches[2] : '98%');
	} else {
		re = /width\s?:\s?(\d{1,3})([px|%])/ig;
		var matches = re.exec(attributes);
		if(matches != null && matches.length) {
			width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] : '98%') : (matches[1] <= 560 ? matches[1] : '98%');
		}
	}
	return width == '' ? '[table]' : '[table=' + width + ']';
}

function tdtag(attributes) {

	var colspan = 1;
	var rowspan = 1;
	var width = '';

	re = /colspan=(["']?)(\d{1,2})(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		colspan = matches[2];
	}

	re = /rowspan=(["']?)(\d{1,2})(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		rowspan = matches[2];
	}

	re = /width=(["']?)(\d{1,3}%?)(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		width = matches[2];
	}

	return in_array(width, ['', '0', '100%']) ?
		(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
		'[td=' + colspan + ',' + rowspan + ',' + width + ']';
}

function trim(str) {
	return (str.replace(/(\s+)$/g, '')).replace(/^\s+/g, '');
}

/**********************************************************************/

var editbox = editwin = editdoc = null;
var cursor = -1;
var stack = new Array();


function expandoptions(id)
{
	var a = document.getElementById(id);
	if(a.style.display=='')
	{
		a.style.display='none';
	}
	else
	{
		a.style.display='';
	}
}

function cloneObj(oClone, oParent, count) {
	if(oParent.childNodes.length < count) {
		var newNode = oClone.cloneNode(true);
		oParent.appendChild(newNode);
		
		return true;
	} 
	return false;	
}

function delObj(oParent, count) {
	if(oParent.childNodes.length > count) {
		oParent.removeChild(oParent.lastChild);
		return true;
	}
	return false;
}

function setfileid(maxup){
	str='';
	if(!document.getElementById("upcount").value){
		document.getElementById("upcount").value=1;
	}
	if(document.getElementById("upcount").value > maxup){
		alert('您最多只能同时上传 '+maxup+' 个文件!');
		document.getElementById("upcount").value = maxup;
		setfileid();
	}
	else
	{
		for(i=1;i<=document.getElementById("upcount").value;i++)
			str+='<div id="divfileItem" style="padding-top:4px"> 上传附件: <input type="file" name="fileitemid'+i+'" size="60" onBlur=this.className="colorblur"; onfocus=this.className="colorfocus"; class="colorblur"></div>';
			document.getElementById("divfileItem").innerHTML=str;
		}
}

function clonePoll(maxpoll){
	if(!cloneObj(document.getElementById('divPollItem'), document.getElementById('polloptions') ,maxpoll)){
		alert('投票项不能多于 ' + maxpoll + ' 个');
	}
	document.all("pollitemid")[document.all('pollitemid').length-1].value = "";
}

function newEditor(mode, initialtext) {

	wysiwyg = parseInt(mode);
	if(!(is_ie || is_moz || (is_opera && opera.version() >= 9))) {
		allowswitcheditor = wysiwyg = 0;
	}
	var bbcodemode = document.getElementById('bbcodemode');
	var wysiwygmode = document.getElementById('wysiwygmode');
	bbcodemode.className = wysiwyg ? 'editor_switcher' : 'editor_switcher_highlight';
	wysiwygmode.className = wysiwyg ? 'editor_switcher_highlight' : 'editor_switcher';
	if(!allowswitcheditor) {
		document.getElementById(editorid + '_switcher').style.display = 'none';
	}

	document.getElementById(editorid + '_cmd_table').disabled = wysiwyg ? false : true;

	if(wysiwyg) {
		if(document.getElementById(editorid + '_iframe')) {
			editbox = document.getElementById(editorid + '_iframe');
		} else {
			var iframe = document.createElement('iframe');
			editbox = textobj.parentNode.appendChild(iframe);
			editbox.id = editorid + '_iframe';
		}

		editwin = editbox.contentWindow;
		editdoc = editwin.document;
		writeEditorContents(isUndefined(initialtext) ?  textobj.value : initialtext);
	} else {
		editbox = textobj;
		editwin = textobj;
		editdoc = textobj;
		if(!isUndefined(initialtext)) {
			writeEditorContents(initialtext);
		}
		addSnapshot(textobj.value);
	}
	setEditorEvents();
}


function writeEditorContents(text) {
	if(wysiwyg) {
		if(text == '' && is_moz) {
			text = '<br />';
		}
		if(editdoc && editdoc.initialized) {
			editdoc.body.innerHTML = text;
		} else {
			editdoc.designMode = 'on';
			editdoc = editwin.document;
			editdoc.open('text/html', 'replace');
			editdoc.write(text);
			editdoc.close();
			editdoc.body.contentEditable = true;
			editdoc.initialized = true;
		}
	} else {
		textobj.value = text;
	}

	setEditorStyle();

}

function getEditorContents() {
	return wysiwyg ? editdoc.body.innerHTML : editdoc.value;
}

function setEditorStyle() {
	if(wysiwyg) {
		textobj.style.display = 'none';
		editbox.style.display = '';

		if(is_moz || is_opera) {
			for(var ss = 0; ss < document.styleSheets.length; ss++) {
				if(document.styleSheets[ss].cssRules.length <= 0) {
					continue;
				}
				for(var i = 0; i < document.styleSheets[ss].cssRules.length; i++) {
					if(document.styleSheets[ss].cssRules[i].selectorText == '.wysiwyg') {
						var newss = editdoc.createElement('style');
						newss.type = 'text/css';
						newss.innerHTML = document.styleSheets[ss].cssRules[i].cssText + ' p { margin: 0px; }';
						editdoc.documentElement.childNodes[0].appendChild(newss);
						editdoc.body.style.fontSize = document.styleSheets[ss].cssRules[i].style.fontSize;
						editdoc.body.style.fontFamily = document.styleSheets[ss].cssRules[i].style.fontFamily;
					}
				}
			}
			editbox.style.border = '0px';
		} else if(is_ie) {
			if(document.styleSheets['css']) {
				editdoc.createStyleSheet().cssText =document.styleSheets['css'].cssText + ' p { margin: 0px; }';
				//editdoc.body.className = 'mkall';
			}
			editdoc.body.style.border = '1px';
		}
		//css样式
		//editdoc.createStyleSheet().cssText=$.ajax({ url: "/"+_str_UserID+"/css/Editor/", async: false }).responseText;
		editbox.style.width = textobj.style.width;
		editbox.style.height = textobj.style.height;
		editdoc.body.style.backgroundColor = '#FFFFFF';
	} else {
		var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
		if(iframe) {
			textobj.style.display = '';
			textobj.style.width = iframe.style.width;
			textobj.style.height = iframe.style.height;
			iframe.style.display = 'none';
		}
	}
}

function setEditorEvents() {
	if(wysiwyg) {
		if(is_moz || is_opera) {
			editdoc.addEventListener('mouseup', function(e) {setContext(); popupmenu.hide();}, true);
			editdoc.addEventListener('keyup', function(e) {setContext();}, true);
			editwin.addEventListener('focus', function(e) {this.hasfocus = true;}, true);
			editwin.addEventListener('blur', function(e) {this.hasfocus = false;}, true);
			editwin.addEventListener('keydown', function(e) {ctlent(e);}, true);
		} else {
			editdoc.onmouseup = function(e) {setContext(); popupmenu.hide();};
			editdoc.onkeyup = function(e) {setContext();};
			if(editdoc.attachEvent) {
				editdoc.body.attachEvent("onkeydown", ctlent);
			}
		}
	}
	editwin.onfocus = function(e) {this.hasfocus = true;};
	editwin.onblur = function(e) {this.hasfocus = false;};
}


function alipays(){
	var arr = showModalDialog("images/common/alipay.htm", "", "dialogWidth:22em; dialogHeight:35em; status:0;help:0");
	if (arr != null){
		insertText(arr);
		return false;
	}
}

function forswf()
{
	var arr = showModalDialog("images/common/swf.htm", "", "dialogWidth:30em; dialogHeight:10em; status:0; help:0");
	if (arr != null){
		var ss;
		ss=arr.split("*")
		path=ss[0];
		row=ss[1];
		col=ss[2];
		var string;
		string="[flash="+row+","+col+"]"+path+"[/flash]"
		insertText(string);
	}
	else return false;;
}

function forwmv()
{
	var arr = showModalDialog("images/common/wmv.htm", "", "dialogWidth:30em; dialogHeight:14em; status:0; help:0");
	
	if (arr != null){
		var ss;
		ss=arr.split("*")
		path=ss[0];
		autostart=ss[1];
		width=ss[2];
		height=ss[3];
		ran=rand();
		var string;
		string="[MP="+ width +","+ height +","+ autostart +"]"+ path +"[/MP]";
		insertText(string);
	}
	else return false;
}

function rand() {
	return parseInt((1000)*Math.random()+1);
}

function forrm()
{
	var arr = showModalDialog("images/common/rm.htm", "", "dialogWidth:30em; dialogHeight:14em; status:0; help:0");
	
	if (arr != null)
	{
		var ss;
		ss = arr.split("*")
		path = ss[0];
		row = ss[1];
		col = ss[2];
		autostart = ss[3];
		ran = rand();
		var string;
		string = "[RM="+ row +","+ col +","+ autostart +"]"+ path +"[/RM]";
		insertText(string);
	}
	else return false;
}

function wrapTags(tagname, useoption, selection) {

	if(tagname=='code') {
		applyFormat('removeformat');
	}

	if(isUndefined(selection)) {
		var selection = getSel();
		if(selection === false) {
			selection = '';
		} else {
			selection += '';
		}
	}

	if(useoption === true) {
		var option = showPrompt(construct_phrase(lang['enter_tag_option'], ('[' + tagname + ']')), '');
		if(option = verifyPrompt(option)) {
			var opentag = '[' + tagname + '=' + option + ']';
		} else {
			return false;
		}
	} else if(useoption !== false) {
		var opentag = '[' + tagname + '=' + useoption + ']';
	} else {
		var opentag = '[' + tagname + ']';
	}

	var closetag = '[/' + tagname + ']';
	var text = opentag + selection + closetag;
	insertText(text, mb_strlen(opentag), mb_strlen(closetag));
	return false;
}

function applyFormat(cmd, dialog, argument) {

	if(wysiwyg) {
		editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
		return false;
	}
	switch(cmd) {
		case 'bold':
		case 'italic':
		case 'underline':
			wrapTags(cmd.substr(0, 1), false);
			break;
		case 'justifyleft':
		case 'justifycenter':
		case 'justifyright':
			wrapTags('align', cmd.substr(7));
			break;
		case 'indent':
			wrapTags(cmd, false);
			break;
		case 'fontname':
			wrapTags('font', argument);
			break;
		case 'fontsize':
			wrapTags('size', argument);
			break;
		case 'forecolor':
			wrapTags('color', argument);
			break;
		case 'createlink':
			var sel = getSel();
			if(sel) {
				wrapTags('url', argument);
			} else {
				wrapTags('url', argument, argument);
			}
			break;
		case 'insertimage':
			wrapTags('img', false, argument);
			break;
	}
}

function customTags(tagname, params) {
	applyFormat('removeformat');

	if(custombbcodes[tagname].indexOf(']') == -1) {
		custombbcodes[tagname] = '[' + tagname + '][/' + tagname + ']';
	}

	if(params == 1) {
		var selection = getSel();
		if(selection === false) {
			selection = '';
		} else {
			selection += '';
		}

		var opentag = '[' + tagname + ']';
		var closetag = '[/' + tagname + ']';
		var text = opentag + selection + closetag;
		selection == '' ? insertText(custombbcodes[tagname], mb_strlen('[' + tagname + ']'), mb_strlen('[/' + tagname + ']')) : insertText(text, mb_strlen(opentag), mb_strlen(closetag));
	} else {
		insertText(custombbcodes[tagname], custombbcodes[tagname].indexOf(']') + 1, mb_strlen('[/' + tagname + ']'));
	}

	return false;
}

function webcode(cmd, arg) {
	if(cmd != 'redo') {
		addSnapshot(getEditorContents());
	}

	checkFocus();

	if(in_array(cmd, ['quote', 'code'])) {
		var ret = wrapTags(cmd, false);
	} else if(cmd.substr(0, 6) == 'custom') {
		var ret = customTags(cmd.substr(8), cmd.substr(6, 1));
	} else if(!wysiwyg && cmd == 'removeformat') {
		var simplestrip = new Array('b', 'i', 'u');
		var complexstrip = new Array('font', 'color', 'size');

		var str = getSel();
		if(str === false) {
			return;
		}
		for(var tag in simplestrip) {
			str = stripSimple(simplestrip[tag], str);
		}
		for(var tag in complexstrip) {
			str = stripComplex(complexstrip[tag], str);
		}
		insertText(str);
	} else if(!wysiwyg && cmd == 'undo') {
		addSnapshot(getEditorContents());
		moveCursor(-1);
		if((str = getSnapshot()) !== false) {
			editdoc.value = str;
		}
	} else if(!wysiwyg && cmd == 'redo') {
		moveCursor(1);
		if((str = getSnapshot()) !== false) {
			editdoc.value = str;
		}
	} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
		var listtype = cmd == 'insertorderedlist' ? '1' : '';
		var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
		var closetag = '[/list]';

		if(txt = getSel()) {
			var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
			txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
			insertText(txt, mb_strlen(txt), 0);
		} else {
			insertText(opentag + closetag, opentag.length, closetag.length);

			while(listvalue = prompt(lang['enter_list_item'], '')) {
				if(is_opera && opera.version() > 8) {
					listvalue = '\n' + '[*]' + listvalue;
					insertText(listvalue, mb_strlen(listvalue) + 1, 0);
				} else {
					listvalue = '[*]' + listvalue + '\n';
					insertText(listvalue, mb_strlen(listvalue), 0);
				}
			}
		}
	} else if(!wysiwyg && cmd == 'outdent') {
		var sel = getSel();
		sel = stripSimple('indent', sel, 1);
		insertText(sel);
	} else if(cmd == 'createlink') {
		if(wysiwyg) {
			if(is_moz || is_opera) {
				var url = showPrompt(lang['enter_link_url'], 'http://');
				if((url = verifyPrompt(url)) !== false) {
					if(getSel()) {
						applyFormat('unlink');
						applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
					} else {
						insertText('<a href="' + url + '">' + url + '</a>');
					}
				}
			} else {
				applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
			}
		} else {
			promptLink('url', lang['enter_link_url'], 'http://');
		}
	} else if(!wysiwyg && cmd == 'unlink') {
		var sel = getSel();
		sel = stripSimple('url', sel);
		sel = stripComplex('url', sel);
		insertText(sel);
	} else if(cmd == 'email') {
		if(wysiwyg) {
			var email = showPrompt(lang['enter_email_link'], '');
			email = verifyPrompt(email);

			if(email === false) {
				applyFormat('unlink');
			} else {
				var selection = getSel();
				insertText('<a href="mailto:' + email + '">' + (selection ? selection : email) + '</a>', (selection ? true : false));
			}
		} else {
			promptLink('email', lang['enter_email_link'], '');
		}
	} else if(cmd == 'insertimage') {
		var img = showPrompt(lang['enter_image_url'], 'http://');
		if(img = verifyPrompt(img)) {
			return applyFormat('insertimage', false, img);
		} else {
			return false;
		}
	} else if(cmd == 'table') {
		if(wysiwyg) {
			if(isUndefined(rows)) {
				var rows = showPrompt(lang['enter_table_rows'], '2');
			}
			if(rows != 'null' && isUndefined(columns)) {
				var columns = showPrompt(lang['enter_table_columns'], '2');
			}
			if(!isUndefined(columns) && columns != 'null') {
				rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
				columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
				var html = '<table cellspacing="1" cellpadding="4" width="50%" align="center" style="background: ' + BORDERCOLOR + '">';
				for (var row = 0; row < rows; row++) {
					html += '<tr bgcolor="' + ALTBG2 + '">\n';
					for (col = 0; col < columns; col++) {
						html += '<td>&nbsp;</td>\n';
					}
					html+= '</tr>\n';
				}
				html += '</table>\n';
				insertText(html);
			}
		}
		return false;
	} else {
		var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
	}

	if(cmd != 'undo') {
		addSnapshot(getEditorContents());
	}
	if(wysiwyg) {
		setContext(cmd);
		if(cmd == 'forecolor') {
			document.getElementById(editorid + '_color_bar').style.backgroundColor = arg;
		}
	}
	checkFocus();
	return ret;
}

function setContext(cmd) {
	var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
	for(var i in contextcontrols) {
		var obj = document.getElementById(editorid + '_cmd_' + contextcontrols[i]);
		if(obj != null) {
			var state = editdoc.queryCommandState(contextcontrols[i]);
			if(isUndefined(obj.state)) {
				obj.state = false;
			}
			if(obj.state != state) {
				obj.state = state;
				buttonContext(obj, (obj.id.substr(obj.id.indexOf('_cmd_') + 5) == cmd ? 'mouseover' : 'mouseout'));
			}
		}
	}

	var fs = editdoc.queryCommandValue('fontname');
	if(fs == '' && !is_ie && window.getComputedStyle) {
		fs = editdoc.body.style.fontFamily;
	} else if(fs == null) {
		fs = '';
	}
	if(fs != document.getElementById(editorid + '_font_out').fontstate) {
		thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
		document.getElementById(editorid + '_font_out').innerHTML = thingy;
		document.getElementById(editorid + '_font_out').fontstate = fs;
	}

	var ss = editdoc.queryCommandValue('fontsize');
	if(ss == null || ss == '') {
		ss = formatFontsize(editdoc.body.style.fontSize);
	}
	if(ss != document.getElementById(editorid + '_size_out').sizestate) {
		if(document.getElementById(editorid + '_size_out').sizestate == null) {
			document.getElementById(editorid + '_size_out').sizestate = '';
		}
		document.getElementById(editorid + '_size_out').innerHTML = ss;
		document.getElementById(editorid + '_size_out').sizestate = ss;
	}

	var cs = editdoc.queryCommandValue('forecolor');
	document.getElementById(editorid + '_color_bar').style.backgroundColor = rgbToColor(cs);
}

function buttonContext(obj, state) {
	if(state == 'mouseover') {
		var mode = obj.state ? 'down' : 'hover';
		if(obj.mode != mode) {
			obj.mode = mode;
			obj.className = 'editor_button' + mode;
		}
	} else {
		var mode = obj.state ? 'selected' : 'normal';
		if(obj.mode != mode) {
			obj.mode = mode;
			obj.className = mode == 'selected' ? 'editor_buttonselected' : 'editor_button' + 'normal';
		}
	}
}

function menuContext(obj, state) {
	obj.style.cursor = is_ie ? 'hand' : 'pointer';
	var mode = state == 'mouseover' ? 'hover' : 'normal';
	obj.className = 'editor_button' + mode;
	var tds = findtags(obj, 'td');
	for(var i = 0; i < tds.length; i++) {
		if(tds[i].id == editorid + '_menu') {
			tds[i].className = 'editor_menu' + mode;
		} else if(tds[i].id == editorid + '_colormenu') {
			tds[i].className = 'editor_colormenu' + mode;
		}
	}
}

function colorContext(obj, state) {
	obj.style.cursor = is_ie ? 'hand' : 'pointer';
	var mode = state == 'mouseover' ? 'hover' : 'normal';
	obj.className = 'editor_color' + mode;
}

function getSel() {
	if(wysiwyg) {
		if(is_moz || is_opera) {
			selection = editwin.getSelection();
			checkFocus();
			range = selection ? selection.getRangeAt(0) : editdoc.createRange();
			return readNodes(range.cloneContents(), false);
		} else {
			var range = editdoc.selection.createRange();
			if(range.htmlText && range.text) {
				return range.htmlText;
			} else {
				var htmltext = '';
				for(var i = 0; i < range.length; i++) {
					htmltext += range.item(i).outerHTML;
				}
				return htmltext;
			}
		}
	} else {
		if(!isUndefined(editdoc.selectionStart)) {
			return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
		} else if(document.selection && document.selection.createRange) {
			return document.selection.createRange().text;
		} else if(window.getSelection) {
			return window.getSelection() + '';
		} else {
			return false;
		}
	}
}

function insertText(text, movestart, moveend) {
	if(wysiwyg) {
		if(is_moz || is_opera) {
			var fragment = editdoc.createDocumentFragment();
			var holder = editdoc.createElement('span');
			holder.innerHTML = text;

			while(holder.firstChild) {
				fragment.appendChild(holder.firstChild);
			}
			insertNodeAtSelection(fragment);
		} else {
			checkFocus();
			if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
				movestart = false;
				editdoc.selection.clear();
			}

			var sel = editdoc.selection.createRange();

			sel.pasteHTML(text);

			if(text.indexOf('\n') == -1) {
				if(!isUndefined(movestart)) {
					sel.moveStart('character', -mb_strlen(text) +movestart);
					sel.moveEnd('character', -moveend);
				} else if(movestart != false) {
					sel.moveStart('character', -mb_strlen(text));
				}
			}
		}
	} else {

		checkFocus();
		if(!isUndefined(editdoc.selectionStart)) {

			var opn = editdoc.selectionStart + 0;

			editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);

			if(!isUndefined(movestart)) {
				editdoc.selectionStart = opn + movestart;
				editdoc.selectionEnd = opn + mb_strlen(text) - moveend;
			} else if(movestart !== false) {
				editdoc.selectionStart = opn;
				editdoc.selectionEnd = opn + mb_strlen(text);
			}
		} else if(document.selection && document.selection.createRange) {

			var sel = document.selection.createRange();
			sel.text = text.replace(/\r?\n/g, '\r\n');

			if(!isUndefined(movestart)) {
				sel.moveStart('character', -mb_strlen(text) +movestart);
				sel.moveEnd('character', -moveend);
			} else if(movestart !== false) {
				sel.moveStart('character', -mb_strlen(text));
			}
			sel.select();
		} else {
			editdoc.value += text;
		}
	}
}

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}


function showPrompt(dialogtxt, defaultval) {
	return trim(prompt(dialogtxt, defaultval) + '');
}

function verifyPrompt(str) {
	if(in_array(str, ['http://', 'null', 'undefined', 'false', '']) || str == null || str == false) {
		return false;
	} else {
		return str;
	}
}

function promptLink(tagname, phrase, iprompt) {
	var value = showPrompt(phrase, iprompt);
	if((value = verifyPrompt(value)) !== false) {
		if(getSel()) {
			applyFormat('unlink');
			wrapTags(tagname, value);
		} else {
			wrapTags(tagname, value, value);
		}
	}
	return true;
}

function trim(str) {
	return (str.replace(/(\s+)$/g, '')).replace(/^\s+/g, '');
}

function stripSimple(tag, str, iterations) {
	var opentag = '[' + tag + ']';
	var closetag = '[/' + tag + ']';

	if(isUndefined(iterations)) {
		iterations = -1;
	}
	while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
		iterations --;
		if((stopindex = stripos(str, closetag)) !== false) {
			var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
			str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
		} else {
			break;
		}
	}
	return str;
}

function stripComplex(tag, str, iterations) {
	var opentag = '[' + tag + '=';
	var closetag = '[/' + tag + ']';

	if(isUndefined(iterations)) {
		iterations = -1;
	}
	while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
		iterations --;
		if((stopindex = stripos(str, closetag)) !== false) {
			var openend = stripos(str, ']', startindex);
			if(openend !== false && openend > startindex && openend < stopindex) {
				var text = str.substr(openend + 1, stopindex - openend - 1);
				str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
			} else {
				break;
			}
		} else {
			break;
		}
	}
	return str;
}

function stripos(haystack, needle, offset) {
	if(isUndefined(offset)) {
		offset = 0;
	}
	var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
}

function switchEditor(mode) {

	mode = parseInt(mode);
	if(mode == wysiwyg || !allowswitcheditor)  {
		return;
	}
	if(!mode) {
		var controlbar = document.getElementById(editorid + '_controls');
		var controls = new Array();
		var buttons = findtags(controlbar, 'div');
		var buttonslength = buttons.length;
		for(var i = 0; i < buttonslength; i++) {
			if(buttons[i].id) {
				controls[controls.length] = buttons[i].id;
			}
		}
		var controlslength = controls.length;
		for(var i = 0; i < controlslength; i++) {
			var control = document.getElementById(controls[i]);

			if(control.id.indexOf(editorid + '_cmd_') != -1) {
				control.className = 'editor_buttonnormal';
				control.state = false;
				control.mode = 'normal';
			} else if(control.id.indexOf(editorid + '_popup_') != -1) {
				control.state = false;
			}
		}
	}
	cursor = -1;
	stack = new Array();
	document.getElementById(editorid + '_font_out').innerHTML = lang['fontname'];
	document.getElementById(editorid + '_size_out').innerHTML = lang['fontsize'];
	document.getElementById(editorid + '_font_out').fontstate = null;
	document.getElementById(editorid + '_size_out').sizestate = null;
	document.getElementById(editorid + '_color_bar').style.backgroundColor = '#000000';
	var parsedtext = getEditorContents();
	parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
	wysiwyg = mode;
	document.getElementById(editorid + '_mode').value = mode;

	newEditor(mode, parsedtext);
	checkFocus();
}

function formatFontsize(csssize) {
	switch(csssize) {
		case '7.5pt':
		case '10px': return 1;
		case '10pt': return 2;
		case '12pt': return 3;
		case '14pt': return 4;
		case '18pt': return 5;
		case '24pt': return 6;
		case '36pt': return 7;
		default:     return lang['fontsize'];
	}
}

function rgbToColor(forecolor) {
	if(!is_moz && !is_opera) {
		return rgbhexToColor((forecolor & 0xFF).toString(16), ((forecolor >> 8) & 0xFF).toString(16), ((forecolor >> 16) & 0xFF).toString(16));
	}
	if(forecolor == '' || forecolor == null) {
		forecolor = window.getComputedStyle(editdoc.body, null).getPropertyValue('color');
	}
	if(forecolor.toLowerCase().indexOf('rgb') == 0) {
		var matches = forecolor.match(/^rgb\s*\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)$/);
		if(matches) {
			return rgbhexToColor((matches[1] & 0xFF).toString(16), (matches[2] & 0xFF).toString(16), (matches[3] & 0xFF).toString(16));
		} else {
			return rgbToColor(null);
		}
	} else {
		return forecolor;
	}
}

function rgbhexToColor(r, g, b) {
	var coloroptions = {'#000000' : 'Black', '#a0522d' : 'Sienna', '#556b2f' : 'DarkOliveGreen', '#006400' : 'DarkGreen', '#483d8b' : 'DarkSlateBlue', '#000080' : 'Navy', '#4b0082' : 'Indigo', '#2f4f4f' : 'DarkSlateGray', '#8b0000' : 'DarkRed', '#ff8c00' : 'DarkOrange', '#808000' : 'Olive', '#008000' : 'Green', '#008080' : 'Teal', '#0000ff' : 'Blue', '#708090' : 'SlateGray', '#696969' : 'DimGray', '#ff0000' : 'Red', '#f4a460' : 'SandyBrown', '#9acd32' : 'YellowGreen', '#2e8b57' : 'SeaGreen', '#48d1cc' : 'MediumTurquoise', '#4169e1' : 'RoyalBlue', '#800080' : 'Purple', '#808080' : 'Gray', '#ff00ff' : 'Magenta', '#ffa500' : 'Orange', '#ffff00' : 'Yellow', '#00ff00' : 'Lime', '#00ffff' : 'Cyan', '#00bfff' : 'DeepSkyBlue', '#9932cc' : 'DarkOrchid', '#c0c0c0' : 'Silver', '#ffc0cb' : 'Pink', '#f5deb3' : 'Wheat', '#fffacd' : 'LemonChiffon', '#98fb98' : 'PaleGreen', '#afeeee' : 'PaleTurquoise', '#add8e6' : 'LightBlue', '#dda0dd' : 'Plum', '#ffffff' : 'White'};
	return coloroptions['#' + (str_pad(r, 2, 0) + str_pad(g, 2, 0) + str_pad(b, 2, 0))];
}

function str_pad(text, length, padstring) {
	text += '';
	padstring += '';

	if(text.length < length) {
		padtext = padstring;

		while(padtext.length < (length - text.length)) {
			padtext += padstring;
		}

		text = padtext.substr(0, (length - text.length)) + text;
	}

	return text;
}

function insertNodeAtSelection(text) {
	checkFocus();

	var sel = editwin.getSelection();
	var range = sel ? sel.getRangeAt(0) : editdoc.createRange();
	sel.removeAllRanges();
	range.deleteContents();

	var node = range.startContainer;
	var pos = range.startOffset;

	switch(node.nodeType) {
		case Node.ELEMENT_NODE:
			if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
				selNode = text.firstChild;
			} else {
				selNode = text;
			}
			node.insertBefore(text, node.childNodes[pos]);
			add_range(selNode);
			break;

		case Node.TEXT_NODE:
			if(text.nodeType == Node.TEXT_NODE) {
				var text_length = pos + text.length;
				node.insertData(pos, text.data);
				range = editdoc.createRange();
				range.setEnd(node, text_length);
				range.setStart(node, text_length);
				sel.addRange(range);
			} else {
				node = node.splitText(pos);
				var selNode;
				if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
					selNode = text.firstChild;
				} else {
					selNode = text;
				}
				node.parentNode.insertBefore(text, node);
				add_range(selNode);
			}
			break;
	}
}

function add_range(node) {
	checkFocus();
	var sel = editwin.getSelection();
	var range = editdoc.createRange();
	range.selectNodeContents(node);
	sel.removeAllRanges();
	sel.addRange(range);
}

function readNodes(root, toptag) {
	var html = "";
	var moz_check = /_moz/i;

	switch(root.nodeType) {
		case Node.ELEMENT_NODE:
		case Node.DOCUMENT_FRAGMENT_NODE:
			var closed;
			if(toptag) {
				closed = !root.hasChildNodes();
				html = '<' + root.tagName.toLowerCase();
				var attr = root.attributes;
				for(var i = 0; i < attr.length; ++i) {
					var a = attr.item(i);
					if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
						continue;
					}
					html += " " + a.name.toLowerCase() + '="' + a.value + '"';
				}
				html += closed ? " />" : ">";
			}
			for(var i = root.firstChild; i; i = i.nextSibling) {
				html += readNodes(i, true);
			}
			if(toptag && !closed) {
				html += "</" + root.tagName.toLowerCase() + ">";
			}
			break;

		case Node.TEXT_NODE:
			html = htmlspecialchars(root.data);
			break;
	}
	return html;
}

function moveCursor(increment) {
	var test = cursor + increment;
	if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
		cursor += increment;
	}
}

function addSnapshot(str) {
	if(stack[cursor] == str) {
		return;
	} else {
		cursor++;
		stack[cursor] = str;

		if(!isUndefined(stack[cursor + 1])) {
			stack[cursor + 1] = null;
		}
	}
}

function getSnapshot() {
	if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
		return stack[cursor];
	} else {
		return false;
	}
}

  var postminchars = parseInt('0');
  var postmaxchars = parseInt('10000');
  var isreid = parseInt('1');
  var disablepostctrl = parseInt('1');
  var bbinsert = parseInt('1');
  function checklength(theform) {
   var message = bbinsert && wysiwyg ? html2bbcode(getEditorContents()) : theform.message.value;
   var showmessage = postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节' : '';
   alert('\n当前长度: ' + message.length + ' 字节\n\n' + showmessage);
  }
  function validate(theform, previewpost) {
   var message = bbinsert && wysiwyg ? html2bbcode(getEditorContents()) : theform.message.value;
    if (theform.subject.value == "" && isreid == 1 ) {
    alert("请完成标题栏。");
    return false;
   } 
    else if ( message ==  "") {
    alert("请完成内容栏。");
    return false;
   }
    else if (theform.subject.value.length > 80 ) {
    alert("您的标题超过 80 个字符的限制。");
    return false;
   }
   if (!disablepostctrl && ((postminchars != 0 && message.length < postminchars) || (postmaxchars != 0 && message.length > postmaxchars))) {
     alert("您的帖子长度不符合要求。\n\n当前长度: "+message.length+" 字节\n系统限制: "+postminchars+" 到 "+postmaxchars+" 字节");
    return false;
   }
   if (!previewpost) {
    theform.topicsubmit.disabled = true;
   }
   theform.message.value = message;
   return true;
  }


     var editorid = 'posteditor';
     var wysiwyg = (is_ie || is_moz || (is_opera && opera.version() >= 9)) && parseInt('1') && bbinsert == 1 ? 1 : 0;
     var allowswitcheditor = parseInt('1');
     var allowhtml = parseInt('0');
     var forumallowhtml = parseInt('0');
     var allowsmilies = parseInt('1');
     var allowbbcode = parseInt('1');
     var allowimgcode = parseInt('1');
     var smilies = new Array();
     for (i=1;i<=31;i++)
     {
     smilies[i]= {'code' : '[em'+i+']', 'url' : i+'.gif'};
     }
     var BORDERCOLOR = "#86B9D6";
     var ALTBG2 = "#FFFFFF";
     function previewpost(){
      if(!validate(document.getElementById('postform'), true)) {
       document.getElementById('subject').focus();
       return;
      }
      document.getElementById("previewmessage").innerHTML = bbcode2html(document.getElementById('postform').message.value);
      document.getElementById("previewtable").style.display = '';
      window.scroll(0, 0);
     }
     function clearcontent() {
      if(wysiwyg && bbinsert) {
       editdoc.body.innerHTML = is_moz ? '<br />' : '';
      } else {
       textobj.value = '';
      }
     }
     function resizeEditor(change) {
      var editorbox = bbinsert ? editbox : textobj;
      var newheight = parseInt(editorbox.style.height, 10) + change;
      if(newheight >= 100) {
       editorbox.style.height = newheight + 'px';
      }
     }
	  var lang    = new Array();
	  lang["enter_tag_option"]  = "请输入 %1 标签的选项:";
	  lang["enter_list_item"] =    "输入一个列表项目.\r\n留空或者点击取消完成此列表.";
	  lang["enter_link_url"]   = "请输入链接的地址:";
	  lang["enter_image_url"]  = "请输入图片链接地址:";
	  lang["enter_email_link"]  = "请输入此链接的邮箱地址:";
	  lang['enter_table_rows']  = "请输入行数，最多 30 行:";
	  lang['enter_table_columns']  = "请输入列数，最多 30 列:";
	  lang['fontname']   = "字体";
	  lang['fontsize']   = "大小";
var fontoptions = new Array("仿宋_GB2312", "黑体", "楷体_GB2312", "宋体", "新宋体", "Tahoma", "Arial", "Impact", "Verdana", "Times New Roman");